//
//  PatientManagerController.m
//  HarmonizePub
//
//  Created by rzhy on 16/9/22.
//  Copyright © 2016年 Zy. All rights reserved.
//

#import "PatientManagerController.h"
#import "Config.h"
#import "AddPatientController.h"
#import "PatientManagerTableViewCell.h"
#import "LoginController.h"

static NSString * const CellIdentifier = @"Cell";

@interface PatientManagerController () <UITableViewDataSource, UITableViewDelegate, LoginControllerDelegate>
{
    NSArray *_dataArray;
    NSIndexPath *_selectIndexPath;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *relieveButton;

@end

@implementation PatientManagerController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    self.title = @"就诊人管理";
    _tableView.layer.cornerRadius = 5.0f;
    _tableView.layer.masksToBounds = YES;
    _tableView.layer.borderWidth = 0.5f;
    _tableView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _relieveButton.layer.cornerRadius = 5.0f;
    _relieveButton.layer.masksToBounds = YES;
    
    UINib *nib = [UINib nibWithNibName:[PatientManagerTableViewCell registerName] bundle:nil];
    [_tableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getPatientList];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if (_selectIndexPath) [self tableView:_tableView didDeselectRowAtIndexPath:_selectIndexPath];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 获取绑定就诊卡列表
- (void)getPatientList {
    NSString *token = [UserDefaultsTool stringForKey:XHToken];
    if ([token isEqualToString:@"0"]) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提 示:" message:@"您还未登录，请先进行登录!" preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        __weak typeof(self) weakSelf = self;
        UIAlertAction *loginAction = [UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            LoginController *login = [[LoginController alloc] init];
            login.delegate = weakSelf;
            [weakSelf presentViewController:login animated:YES completion:nil];
        }];
//        [alertController addAction:cancelAction];
        [alertController addAction:loginAction];
        [self presentViewController:alertController animated:YES completion:nil];
    } else {
        NSDictionary *cookie = @{CookieVaule : token};
        NSDictionary *param = @{@"type" : @"0"};
        [HTTPSTool POSTRequestWithPath:XHGetBrdaList cookie:cookie params:param success:^(NSDictionary * _Nonnull JSON) {
//            XHLog(@"绑定就诊卡列表 -> JSON: %@", JSON)
            _dataArray = JSON[@"data"][@"list"];
            [_tableView reloadData];
            [self storagePatientListDataWithDataArray:JSON[@"data"][@"list"]];
        }];
    }
}

- (void)cancelLogin:(LoginController *)login {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - 储存就诊列表数据
- (void)storagePatientListDataWithDataArray:(NSArray *)dataArray {
    if (!dataArray) return ;
    NSMutableArray *medicalArray = [NSMutableArray array];
    NSMutableArray *inpatientArray = [NSMutableArray array];
    for (NSDictionary *dataDict in dataArray) {
        if ([dataDict[@"bindType"] integerValue] == 1)
            [medicalArray addObject:dataDict];
        else
            [inpatientArray addObject:dataDict];
    }
    NSMutableDictionary *rootDict = [NSMutableDictionary dictionary];
    if (medicalArray.count) [rootDict setValue:medicalArray forKey:XHMedicalListKey];
    if (inpatientArray.count) [rootDict setValue:inpatientArray forKey:XHInpatientLisyKey];
    if (rootDict.allKeys.count) {
        [rootDict writeToFile:XHPatientListPath atomically:YES];
    } else {
        [ZYFileManager deleteFinderAndFileWithPath:XHPatientListPath];
    }
}

#pragma mark - 按钮点击事件
#pragma mark 添加就诊人
- (IBAction)addButtonEvent:(UIButton *)sender {
    AddPatientController *addPatient = [[AddPatientController alloc] init];
    [self.navigationController pushViewController:addPatient animated:YES];
}

#pragma mark 解除绑定
- (IBAction)relieveButtonEvent:(UIButton *)sender {
    if (!_dataArray.count) {
        [self setAlertViewWithMessage:@"并无需要解绑的就诊人!"];
    } else if (!_selectIndexPath) {
        [self setAlertViewWithMessage:@"请先选择要解绑的就诊人!"];
    } else {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提 示:" message:@"是否确定要解绑该就诊人?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        __unsafe_unretained PatientManagerController *weakSelf = self;
        UIAlertAction *relieveAction = [UIAlertAction actionWithTitle:@"解绑" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            NSDictionary *selectDataDict = _dataArray[_selectIndexPath.row];
            NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
            NSDictionary *param = @{@"id" : selectDataDict[@"id"]};
            [HTTPSTool POSTRequestWithPath:XHUnbindBrda cookie:cookie params:param success:^(NSDictionary * _Nonnull JSON) {
//                XHLog(@"解绑就诊卡 -> JSON: %@", JSON)
                [ZYToast showBottomText:@"解绑成功!"];
                [weakSelf tableView:_tableView didDeselectRowAtIndexPath:_selectIndexPath];
                [weakSelf getPatientList];
            }];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:relieveAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

#pragma mark - tableView delegate/dataSource Method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [PatientManagerTableViewCell cellHeight];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PatientManagerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    [cell setCellShowDataWithDataDictionary:_dataArray[indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    PatientManagerTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.isSelect = YES;
    _selectIndexPath = indexPath;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    PatientManagerTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.isSelect = NO;
}

- (void)setAlertViewWithMessage:(NSString *)msg {
    UIAlertController *alertContriller = [UIAlertController alertControllerWithTitle:@"提 示:" message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确 定" style:UIAlertActionStyleDefault handler:nil];
    [alertContriller addAction:defaultAction];
    [self presentViewController:alertContriller animated:YES completion:nil];
}

@end
